package com.jsj.servlet.ch4;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
		String nowTime=sdf.format(new Date());
		PrintWriter out=response.getWriter();
		
		String lastVisitTime="";
		int visitedCount=0;
		//获取客户端浏览器保存的所有cookie
		Cookie[] cookies=request.getCookies();
		if(cookies !=null) {
			for(Cookie cookie:cookies) {
				if("lastVisitTime".equals(cookie.getName())) {
					lastVisitTime=cookie.getValue();
				}
				if("visitedCount".equals(cookie.getName())) {
					visitedCount=Integer.valueOf(cookie.getValue());
				}				
			}
		}
		//若曾经访问过，输出上次访问时间
		if(!"".equals(lastVisitTime)) {
			out.println("您上一次的访问时间是：" + lastVisitTime);
		}
		//输出访问次数
		out.println("您是第" + (visitedCount+1) +"次访问本站！");
		
		//以本次访问时间重建同名cookie
		Cookie lastVisitTimeCookie = new Cookie("lastVisitTime",nowTime);
		//设置最大存活时间
		lastVisitTimeCookie.setMaxAge(365*24*60*60);
		
		//以新访问次数重建同名Cookie
		Cookie visitedCountCookie = new Cookie("visitedCount",String.valueOf(visitedCount + 1));
		visitedCountCookie.setMaxAge(365*24*60*60);
		
		//将新建的Cookie响应到客户端
		response.addCookie(lastVisitTimeCookie);
		response.addCookie(visitedCountCookie);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
}
